import router from '../router';
import store from '../store';
import { menusToRoutes, resetTokenAndClearUser } from '../utils';
import { LoadingBar } from 'iview';
import { getMenu } from '@/api/system/login';

// 是否有菜单数据
let hasMenus = false;

router.beforeEach(async (to, from, next) => {
    LoadingBar.start();

    if (localStorage.getItem('token')) {
        if (to.path === '/login') {
            next({ path: '/' });
        } else {
            if (hasMenus) {
                next();
            } else {
                try {
                    // 请求后端数据以生成路由
                    const response = await getMenu(); // 应该返回Promise
                    const menuItems = response.data; // 假设后端返回的数据格式正确

                    // 更新store中的菜单项
                    store.commit('setMenus', menuItems);

                    // 使用store中的新数据生成路由
                    const routes = menusToRoutes(store.state.menuItems);
                    // 动态添加路由
                    router.addRoutes(routes);

                    hasMenus = true;

                    // 继续导航
                    next({ path: to.path || '/' });
                } catch (error) {
                    console.error(error);
                    resetTokenAndClearUser();
                    next(`/login?redirect=${to.path}`);
                }
            }
        }
    } else {
        hasMenus = false;
        if (to.path === '/login') {
            next();
        } else {
            next(`/login?redirect=${to.path}`);
        }
    }
});

router.afterEach(() => {
    LoadingBar.finish();
});